import {Pipe, PipeTransform, Injectable} from '@angular/core';
import {DateFormatter} from "@angular/common/src/facade/intl";
import {isBlank, isDate, isNumber, isPresent, DateWrapper, StringMapWrapper} from '../common';
import {InvalidPipeArgumentException} from "@angular/common/src/pipes/invalid_pipe_argument_exception";

var defaultLocale: string = 'zh-CN';

@Pipe({name: 'dateFormat', pure: true})
@Injectable()
export class DateFormatPipe implements PipeTransform {
    static _ALIASES: {[key: string]: String} = {
        'medium': 'yMMMdjms',
        'short': 'yMdjm',
        'fullDate': 'yMMdd HH:mm:ss',
        'time': 'HH:mm:ss',
        'longDate': 'yMMMMd',
        'mediumDate': 'yMMdd',
        'shortDate': 'yMd',
        'mediumTime': 'jms',
        'shortTime': 'jm'
    };
    transform(value: any , pattern?: string): any {
        if (isBlank(value)) return null;

        if (!this.supports(value)) {
            throw new InvalidPipeArgumentException(DateFormatPipe, value);
        }

        pattern = isPresent(pattern) ? pattern : 'mediumDate';
        if (isNumber(value)) {
            value = DateWrapper.fromMillis(value);
        }
        if (StringMapWrapper.contains(DateFormatPipe._ALIASES, pattern)) {
            pattern = <string>StringMapWrapper.get(DateFormatPipe._ALIASES, pattern);
        }
        return DateFormatter.format(value, defaultLocale, pattern);

    }

    supports(obj: any): boolean { return isDate(obj) || isNumber(obj); }
}
